'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import {
  Box,
  Container,
  Typography,
  Paper,
  Grid,
  Button,
  Chip,
  Divider,
  CircularProgress,
  Alert,
  Breadcrumbs,
  Avatar,
} from '@mui/material';
import {
  BusinessCenter as BusinessCenterIcon,
  LocationOn as LocationOnIcon,
  School as SchoolIcon,
  AccessTime as AccessTimeIcon,
  AttachMoney as AttachMoneyIcon,
  Work as WorkIcon,
} from '@mui/icons-material';
import Navbar from '@/components/Navbar';
import ResumeSubmitForm from '@/components/recruitment/ResumeSubmitForm';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';

export default function JobDetailPage({ params }: { params: { id: string } }) {
  const router = useRouter();
  const [job, setJob] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showResumeForm, setShowResumeForm] = useState(false);
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  useEffect(() => {
    // 检查用户是否登录
    const token = localStorage.getItem('token');
    setIsLoggedIn(!!token);

    // 获取职位详情
    const fetchJobDetail = async () => {
      try {
        const response = await fetch(`/api/recruitment/job-detail/${params.id}`);
        
        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.error || '获取职位详情失败');
        }
        
        const data = await response.json();
        setJob(data.job);
      } catch (err) {
        setError((err as Error).message);
      } finally {
        setLoading(false);
      }
    };

    fetchJobDetail();
  }, [params.id]);

  // 处理投递简历
  const handleSubmitResume = () => {
    if (!isLoggedIn) {
      // 如果未登录，跳转到登录页面
      localStorage.setItem('redirectAfterLogin', `/recruitment/job/${params.id}`);
      router.push('/auth/login');
      return;
    }

    setShowResumeForm(true);
  };

  // 关闭简历表单
  const handleCloseResumeForm = () => {
    setShowResumeForm(false);
  };

  // 简历提交成功
  const handleSubmitSuccess = () => {
    setTimeout(() => {
      setShowResumeForm(false);
    }, 1500);
  };

  if (loading) {
    return (
      <>
        <Container maxWidth="lg" sx={{ py: 8, textAlign: 'center' }}>
          <CircularProgress />
          <Typography variant="h6" sx={{ mt: 2 }}>
            正在加载职位信息...
          </Typography>
        </Container>
      </>
    );
  }

  if (error) {
    return (
      <>
        <Container maxWidth="lg" sx={{ py: 8 }}>
          <Alert severity="error" sx={{ mb: 4 }}>
            {error}
          </Alert>
          <Button
            variant="contained"
            onClick={() => router.push('/recruitment')}
          >
            返回招聘列表
          </Button>
        </Container>
      </>
    );
  }

  if (!job) {
    return (
      <>
        <Container maxWidth="lg" sx={{ py: 8 }}>
          <Alert severity="warning" sx={{ mb: 4 }}>
            职位不存在或已下线
          </Alert>
          <Button
            variant="contained"
            onClick={() => router.push('/recruitment')}
          >
            返回招聘列表
          </Button>
        </Container>
      </>
    );
  }

  return (
    <>
      <Box sx={{ bgcolor: 'background.default', minHeight: '100vh', py: 4 }}>
        <Container maxWidth="lg">
          <Box sx={{ mb: 4 }}>
            <Breadcrumbs aria-label="breadcrumb">
              <Link href="/" passHref>
                <Typography color="inherit" sx={{ display: 'flex', alignItems: 'center' }}>
                  首页
                </Typography>
              </Link>
              <Link href="/recruitment" passHref>
                <Typography color="inherit" sx={{ display: 'flex', alignItems: 'center' }}>
                  企业招聘直通车
                </Typography>
              </Link>
              <Typography color="text.primary">{job.title}</Typography>
            </Breadcrumbs>
          </Box>

          <Grid container spacing={3}>
            <Grid item xs={12} md={8}>
              {/* 职位信息卡片 */}
              <Paper sx={{ p: 3, mb: 3, borderRadius: 2 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2 }}>
                  <Box>
                    <Typography variant="h4" component="h1" gutterBottom>
                      {job.title}
                    </Typography>
                    <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1, mb: 2 }}>
                      <Chip
                        icon={<AttachMoneyIcon />}
                        label={job.salary_range}
                        color="success"
                        variant="outlined"
                      />
                      <Chip
                        icon={<LocationOnIcon />}
                        label={job.location}
                        variant="outlined"
                      />
                      <Chip
                        icon={<WorkIcon />}
                        label={job.job_type}
                        variant="outlined"
                      />
                      <Chip
                        icon={<AccessTimeIcon />}
                        label={job.experience}
                        variant="outlined"
                      />
                      <Chip
                        icon={<SchoolIcon />}
                        label={job.education}
                        variant="outlined"
                      />
                    </Box>
                  </Box>
                  <Button
                    variant="contained"
                    color="primary"
                    size="large"
                    onClick={handleSubmitResume}
                  >
                    投递简历
                  </Button>
                </Box>

                <Divider sx={{ my: 3 }} />

                <Typography variant="h6" gutterBottom>
                  职位描述
                </Typography>
                <Typography variant="body1" paragraph sx={{ whiteSpace: 'pre-line' }}>
                  {job.description}
                </Typography>

                <Typography variant="h6" gutterBottom sx={{ mt: 4 }}>
                  任职要求
                </Typography>
                <Typography variant="body1" paragraph sx={{ whiteSpace: 'pre-line' }}>
                  {job.requirements}
                </Typography>

                <Box sx={{ mt: 4, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Typography variant="body2" color="text.secondary">
                    发布时间: {new Date(job.created_at).toLocaleDateString('zh-CN')} ({formatDistanceToNow(new Date(job.created_at), { addSuffix: true, locale: zhCN })})
                  </Typography>
                  <Button
                    variant="contained"
                    color="primary"
                    onClick={handleSubmitResume}
                  >
                    投递简历
                  </Button>
                </Box>
              </Paper>
            </Grid>

            <Grid item xs={12} md={4}>
              {/* 公司信息卡片 */}
              <Paper sx={{ p: 3, borderRadius: 2 }}>
                <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                  <Avatar
                    src={job.company_logo}
                    alt={job.company_name}
                    sx={{ width: 64, height: 64, mr: 2 }}
                  >
                    <BusinessCenterIcon />
                  </Avatar>
                  <Typography variant="h6">
                    {job.company_name}
                  </Typography>
                </Box>

                <Divider sx={{ my: 2 }} />

                <Box sx={{ mb: 2 }}>
                  <Typography variant="subtitle2" color="text.secondary" gutterBottom>
                    行业
                  </Typography>
                  <Typography variant="body1">
                    {job.company_industry || '未指定'}
                  </Typography>
                </Box>

                <Box sx={{ mb: 2 }}>
                  <Typography variant="subtitle2" color="text.secondary" gutterBottom>
                    公司规模
                  </Typography>
                  <Typography variant="body1">
                    {job.company_size || '未指定'}
                  </Typography>
                </Box>

                <Box sx={{ mb: 2 }}>
                  <Typography variant="subtitle2" color="text.secondary" gutterBottom>
                    公司地址
                  </Typography>
                  <Typography variant="body1">
                    {job.company_location || '未指定'}
                  </Typography>
                </Box>

                {job.company_website && (
                  <Box sx={{ mb: 2 }}>
                    <Typography variant="subtitle2" color="text.secondary" gutterBottom>
                      公司网站
                    </Typography>
                    <Link href={job.company_website} target="_blank" rel="noopener noreferrer">
                      <Typography variant="body1" color="primary">
                        {job.company_website}
                      </Typography>
                    </Link>
                  </Box>
                )}

                {job.company_description && (
                  <Box sx={{ mt: 3 }}>
                    <Typography variant="subtitle2" color="text.secondary" gutterBottom>
                      公司简介
                    </Typography>
                    <Typography variant="body2" sx={{ whiteSpace: 'pre-line' }}>
                      {job.company_description}
                    </Typography>
                  </Box>
                )}
              </Paper>
            </Grid>
          </Grid>
        </Container>
      </Box>

      {/* 简历投递表单对话框 */}
      {showResumeForm && (
        <ResumeSubmitForm
          companyId={job.company_id}
          companyName={job.company_name}
          positionId={job.id}
          positionName={job.title}
          onClose={handleCloseResumeForm}
          onSubmitSuccess={handleSubmitSuccess}
        />
      )}
    </>
  );
}
